package org.spring.zuul.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class MyFilter extends ZuulFilter{

	@Override
	public boolean shouldFilter() {
		// 是否执行该过滤器，此处为true，说明需要过滤  
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();  
        HttpServletRequest request = ctx.getRequest();  
  
        System.out.println(String.format("%s AccessUserNameFilter request to %s", request.getMethod(), request.getRequestURL().toString()));  
        if ("admin".equals(request.getParameter("name"))) {
        	ctx.setSendZuulResponse(false);//设置状态为不路由
        	ctx.setResponseStatusCode(401);// 返回错误码
        	ctx.setResponseBody("{\"result\":\"username is not correct!\"}");// 返回错误内容  
            ctx.set("isSuccess", false);  
        }
		return null;
	}

	@Override
	public String filterType() {
		// 前置过滤器  
//		pre：可以在请求被路由之前调用
//		route：在路由请求时候被调用
//		post：在route和error过滤器之后被调用
//		error：处理请求时发生错误时被调用
		return "pre";
	}

	@Override
	public int filterOrder() {
		// 优先级为0，数字越大，优先级越低  
		return 0;
	}

}
